class AccessibilityHelper {
    constructor(options = {}) {
        this.options = {
            zoomLevels: [1, 1.2, 1.5, 2],
            defaultLang: 'zh-CN',
            ttsEnabled: true,
            imageAltEnabled: true,
            contrastModes: {
                normal: {
                    background: '',
                    text: '',
                    links: ''
                },
                highContrast: {
                    background: '#000000',
                    text: '#FFFFFF',
                    links: '#FFFF00'
                },
                yellowOnBlack: {  // 适合色弱
                    background: '#000000',
                    text: '#FFFF00',
                    links: '#00FF00'
                },
                blackOnWhite: {   // 适合色盲
                    background: '#FFFFFF',
                    text: '#000000',
                    links: '#0000FF'
                }
            },
            hoverRead: true,  // 添加鼠标悬浮朗读选项
            hoverDelay: 500,  // 悬浮多久后开始朗读（毫秒）
            initiallyVisible: true,  // 工具初始是否可见
            speechRates: {
                slow: 0.7,
                normal: 1,
                fast: 1.3,
                veryFast: 1.5
            },
            defaultRate: 'normal',
            fonts: {
                default: 'inherit',
                readable: 'Arial, sans-serif',
                dyslexic: 'OpenDyslexic, Arial, sans-serif',
                large: '18px',
                spacing: '1.5'
            },
            plainTextStyles: {
                fontSize: '16px',
                lineHeight: '1.6',
                fontFamily: 'Arial, sans-serif',
                background: '#ffffff',
                color: '#000000'
            },
            readingGuide: {
                height: '60px',
                color: 'rgba(255, 255, 0, 0.1)',
                borderColor: 'rgba(255, 165, 0, 0.3)'
            },
            enabledButtons: {
                zoom: true,          // 缩放功能
                speech: true,        // 朗读功能
                contrast: true,      // 对比度
                plainText: true,     // 纯文本
                font: true,          // 字体设置
                readingGuide: true,  // 阅读指引
                hoverRead: true,     // 悬浮朗读
                rate: true,          // 语速控制
                animation: true,     // 动画控制
                colorFilter: true,    // 色盲模式
            },
            ...options
        };

        this.currentZoom = 1;
        this.isSpeaking = false;
        this.currentContrastMode = 'normal';
        this.hoverTimeout = null;  // 用于控制悬浮延时
        this.currentHoverUtterance = null;  // 当前悬浮朗读的语音实例
        this.isToolbarVisible = this.options.initiallyVisible;
        this.currentRate = this.options.speechRates[this.options.defaultRate];
        this.currentFont = 'default';
        this.isPlainText = false;
        this.isReadingGuideActive = false;
        
        // 确保在 DOM 加载完成后再初始化
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => this.init());
        } else {
            this.init();
        }
    }

    init() {
        try {
            this.createToolbar();
            // 按需初始化功能
            if (this.options.enabledButtons.zoom) {
                this.initZoom();
            }
            if (this.options.enabledButtons.speech) {
                this.initTTS();
            }
            if (this.options.enabledButtons.contrast) {
                this.initContrastMode();
            }
            if (this.options.enabledButtons.hoverRead) {
                this.initHoverRead();
            }
            if (this.options.enabledButtons.font) {
                this.initFontControl();
            }
            if (this.options.enabledButtons.colorFilter) {
                this.initColorFilters();
            }
            if (this.options.enabledButtons.animation) {
                this.initAnimationControl();
            }
        } catch (error) {
            console.error('无障碍助手初始化失败:', error);
        }
    }

    // 创建工具栏
    createToolbar() {
        // 创建工具栏切换按钮
        const toggleButton = document.createElement('button');
        toggleButton.className = 'accessibility-toggle';
        toggleButton.innerHTML = '无障碍工具';
        toggleButton.setAttribute('aria-label', '切换无障碍工具栏');
        document.body.appendChild(toggleButton);
        // 创建工具栏
        const toolbar = document.createElement('div');
        toolbar.className = 'accessibility-toolbar';
        if (!this.isToolbarVisible) {
            toolbar.classList.add('hidden');
        }
        
        // 按需添加按钮
        const buttons = [];

        // 缩放功能
        if (this.options.enabledButtons.zoom) {
            buttons.push(`
                <button class="zoom-in" title="放大页面">放大</button>
                <button class="zoom-out" title="缩小页面">缩小</button>
            `);
        }

        // 朗读功能
        if (this.options.enabledButtons.speech) {
            buttons.push(`
                <button class="read-page" title="朗读页面">朗读</button>
                <button class="stop-read" title="停止朗读">停止</button>
            `);
        }

        // 纯文本模式
        if (this.options.enabledButtons.plainText) {
            buttons.push(`
                <button class="plain-text" title="纯文本模式">纯文本</button>
            `);
        }

        // 对比度控制
        if (this.options.enabledButtons.contrast) {
            buttons.push(`
                <div class="contrast-control">
                    <button class="contrast-toggle" title="对比度控制">对比度</button>
                    <div class="contrast-menu" style="display: none;">
                        <button data-mode="normal">正常模式</button>
                        <button data-mode="highContrast">高对比度</button>
                        <button data-mode="yellowOnBlack">黄字黑底</button>
                        <button data-mode="blackOnWhite">黑字白底</button>
                    </div>
                </div>
            `);
        }

        // 字体控制
        if (this.options.enabledButtons.font) {
            buttons.push(`
                <div class="font-control">
                    <button class="font-toggle" title="字体设置">字体</button>
                    <div class="font-menu" style="display: none;">
                        <button data-font="default">默认字体</button>
                        <button data-font="readable">易读字体</button>
                        <button data-font="dyslexic">阅读障碍字体</button>
                        <button data-font="large">大字体</button>
                        <button data-font="spacing">加宽间距</button>
                    </div>
                </div>
            `);
        }

        // 阅读指引
        if (this.options.enabledButtons.readingGuide) {
            buttons.push(`
                <button class="reading-guide" title="阅读指引器">阅读指引</button>
            `);
        }

        // 悬浮朗读
        if (this.options.enabledButtons.hoverRead) {
            buttons.push(`
                <button class="hover-read" title="鼠标悬浮朗读">
                    悬浮朗读${this.options.hoverRead ? '开' : '关'}
                </button>
            `);
        }

        // 语速控制
        if (this.options.enabledButtons.rate) {
            buttons.push(`
                <div class="rate-control">
                    <button class="rate-toggle" title="语速控制">语速</button>
                    <div class="rate-menu" style="display: none;">
                        <button data-rate="slow" ${this.currentRate === this.options.speechRates.slow ? 'class="active"' : ''}>慢速</button>
                        <button data-rate="normal" ${this.currentRate === this.options.speechRates.normal ? 'class="active"' : ''}>正常</button>
                        <button data-rate="fast" ${this.currentRate === this.options.speechRates.fast ? 'class="active"' : ''}>快速</button>
                        <button data-rate="veryFast" ${this.currentRate === this.options.speechRates.veryFast ? 'class="active"' : ''}>特快</button>
                    </div>
                </div>
            `);
        }

        // 动画控制
        if (this.options.enabledButtons.animation) {
            buttons.push(`
                <button class="animation-toggle" title="减少动画">减少动画</button>
            `);
        }

        // 色盲模式
        if (this.options.enabledButtons.colorFilter) {
            buttons.push(`
                <div class="color-filter-control">
                    <button class="filter-toggle" title="色盲模式">色盲模式</button>
                    <div class="filter-menu" style="display: none;">
                        <button data-filter="normal">正常视觉</button>
                        <button data-filter="protanopia">红色色盲</button>
                        <button data-filter="deuteranopia">绿色色盲</button>
                        <button data-filter="tritanopia">蓝色色盲</button>
                    </div>
                </div>
            `);
        }

        toolbar.innerHTML = buttons.join('');
        document.body.appendChild(toolbar);
        this.bindToolbarEvents(toolbar, toggleButton);
    }

    // 绑定工具栏事件
    bindToolbarEvents(toolbar, toggleButton) {
        // 基本功能按钮
        if (this.options.enabledButtons.zoom) {
            const zoomIn = toolbar.querySelector('.zoom-in');
            const zoomOut = toolbar.querySelector('.zoom-out');
            if (zoomIn) zoomIn.addEventListener('click', () => this.zoomIn());
            if (zoomOut) zoomOut.addEventListener('click', () => this.zoomOut());
        }

        if (this.options.enabledButtons.speech) {
            const readPage = toolbar.querySelector('.read-page');
            const stopRead = toolbar.querySelector('.stop-read');
            if (readPage) readPage.addEventListener('click', () => this.startReading());
            if (stopRead) stopRead.addEventListener('click', () => this.stopReading());
        }

        // 对比度控制
        if (this.options.enabledButtons.contrast) {
            const contrastToggle = toolbar.querySelector('.contrast-toggle');
            const contrastMenu = toolbar.querySelector('.contrast-menu');
            const rateMenu = toolbar.querySelector('.rate-menu');
          
            if (contrastToggle && contrastMenu) {
                contrastToggle.addEventListener('click', () => {
                    contrastMenu.style.display = contrastMenu.style.display === 'none' ? 'block' : 'none';
                    // 关闭其他菜单
                    if (rateMenu) rateMenu.style.display = 'none';
                });

                contrastMenu.querySelectorAll('button').forEach(button => {
                    button.addEventListener('click', (e) => {
                        e.stopPropagation();
                        this.setContrastMode(button.dataset.mode);
                        contrastMenu.style.display = 'none';
                    });
                });
            }
        }

        // 点击页面其他地方关闭所有菜单
        document.addEventListener('click', (e) => {
            if (!toolbar.contains(e.target)) {
                const menus = {
                    contrast: toolbar.querySelector('.contrast-menu'),
                    rate: toolbar.querySelector('.rate-menu'),
                    font: toolbar.querySelector('.font-menu'),
                    filter: toolbar.querySelector('.filter-menu')
                };

                Object.values(menus).forEach(menu => {
                    if (menu) menu.style.display = 'none';
                });
            }
        });

        // 悬浮朗读控制
        if (this.options.enabledButtons.hoverRead) {
            const hoverButton = toolbar.querySelector('.hover-read');
            if (hoverButton) {
                hoverButton.addEventListener('click', () => {
                    this.options.hoverRead = !this.options.hoverRead;
                    hoverButton.textContent = `悬浮朗读${this.options.hoverRead ? '开' : '关'}`;
                    hoverButton.classList.toggle('active');
                });
            }
        }

        // 语速控制
        if (this.options.enabledButtons.rate) {
            const rateToggle = toolbar.querySelector('.rate-toggle');
            const rateMenu = toolbar.querySelector('.rate-menu');
            
            if (rateToggle && rateMenu) {
                rateToggle.addEventListener('click', () => {
                    rateMenu.style.display = rateMenu.style.display === 'none' ? 'block' : 'none';
                //     // 关闭其他菜单
                //     toolbar.querySelector('.contrast-menu')?.style.display = 'none';
                });

                rateMenu.querySelectorAll('button').forEach(button => {
                    button.addEventListener('click', (e) => {
                        e.stopPropagation();
                        const rate = button.dataset.rate;
                        this.setRate(rate);
                        rateMenu.style.display = 'none';
                        
                        // 更新按钮状态
                        rateMenu.querySelectorAll('button').forEach(btn => {
                            btn.classList.remove('active');
                        });
                        button.classList.add('active');
                    });
                });
            }
        }

        // 纯文本模式切换
        if (this.options.enabledButtons.plainText) {
            toolbar.querySelector('.plain-text')?.addEventListener('click', () => {
                this.togglePlainText();
            });
        }

        // 阅读指引器控制
        if (this.options.enabledButtons.readingGuide) {
            toolbar.querySelector('.reading-guide')?.addEventListener('click', () => {
                this.toggleReadingGuide();
            });
        }

        // 工具栏切换按钮
        toggleButton.addEventListener('click', () => {
            this.toggleToolbar();
        });

        // 字体控制
        if (this.options.enabledButtons.font) {
            const fontToggle = toolbar.querySelector('.font-toggle');
            const fontMenu = toolbar.querySelector('.font-menu');
            
            if (fontToggle && fontMenu) {
                fontToggle.addEventListener('click', () => {
                    fontMenu.style.display = fontMenu.style.display === 'none' ? 'block' : 'none';
                });

                fontMenu.querySelectorAll('button').forEach(button => {
                    button.addEventListener('click', (e) => {
                        e.stopPropagation();
                        this.setFont(button.dataset.font);
                        fontMenu.style.display = 'none';
                    });
                });
            }
        }

        // 动画控制
        if (this.options.enabledButtons.animation) {
            toolbar.querySelector('.animation-toggle')?.addEventListener('click', () => {
                this.toggleReduceMotion();
            });
        }

        // 色盲模式
        if (this.options.enabledButtons.colorFilter) {
            const filterToggle = toolbar.querySelector('.filter-toggle');
            const filterMenu = toolbar.querySelector('.filter-menu');
            
            if (filterToggle && filterMenu) {
                filterToggle.addEventListener('click', () => {
                    filterMenu.style.display = filterMenu.style.display === 'none' ? 'block' : 'none';
                });

                filterMenu.querySelectorAll('button').forEach(button => {
                    button.addEventListener('click', (e) => {
                        e.stopPropagation();
                        this.setColorFilter(button.dataset.filter);
                        filterMenu.style.display = 'none';
                    });
                });
            }
        }
    }

    // 页面缩放功能
    initZoom() {
        try {
            this.zoomContainer = document.createElement('div');
            this.zoomContainer.className = 'zoom-container';
            
            // 保存原始内容
            const originalContent = Array.from(document.body.children).filter(child => {
                return !child.classList.contains('accessibility-toolbar') && 
                       !child.classList.contains('accessibility-toggle');
            });

            // 将内容移动到缩放容器
            originalContent.forEach(element => {
                this.zoomContainer.appendChild(element);
            });

            document.body.appendChild(this.zoomContainer);
        } catch (error) {
            console.error('缩放功能初始化失败:', error);
        }
    }

    zoomIn() {
        const currentIndex = this.options.zoomLevels.indexOf(this.currentZoom);
        if (currentIndex < this.options.zoomLevels.length - 1) {
            this.currentZoom = this.options.zoomLevels[currentIndex + 1];
            this.applyZoom();
        }
    }

    zoomOut() {
        const currentIndex = this.options.zoomLevels.indexOf(this.currentZoom);
        if (currentIndex > 0) {
            this.currentZoom = this.options.zoomLevels[currentIndex - 1];
            this.applyZoom();
        }
    }

    applyZoom() {
        this.zoomContainer.style.transform = `scale(${this.currentZoom})`;
        this.zoomContainer.style.transformOrigin = 'top left';
        document.body.style.minHeight = `${100 * this.currentZoom}vh`;
    }

    // 文字转语音功能
    initTTS() {
        if (!this.options.ttsEnabled) return;
        
        try {
            if ('speechSynthesis' in window) {
                this.speechSynthesis = window.speechSynthesis;
                
                // 等待语音列表加载
                const loadVoices = () => {
                    this.voices = this.speechSynthesis.getVoices();
                };

                loadVoices();
                if (speechSynthesis.onvoiceschanged !== undefined) {
                    speechSynthesis.onvoiceschanged = loadVoices;
                }
            } else {
                console.warn('浏览器不支持语音合成功能');
                this.options.ttsEnabled = false;
            }
        } catch (error) {
            console.error('语音功能初始化失败:', error);
            this.options.ttsEnabled = false;
        }
    }

    startReading() {
        if (this.isSpeaking) {
            this.stopReading();
            return;
        }

        const textNodes = this.getTextNodes();
        if (!textNodes.length) return;

        this.isSpeaking = true;
        this.readNodes(textNodes);
    }

    stopReading() {
        if (this.speechSynthesis) {
            this.speechSynthesis.cancel();
            this.isSpeaking = false;
            this.removeHighlights();
        }
    }

    readNodes(nodes) {
        let currentIndex = 0;

        const readNext = () => {
            if (currentIndex >= nodes.length || !this.isSpeaking) {
                this.stopReading();
                return;
            }

            const node = nodes[currentIndex];
            const text = this.getNodeText(node);

            this.highlightNode(node);
            node.scrollIntoView({ behavior: 'smooth', block: 'center' });

            const utterance = new SpeechSynthesisUtterance(text);
            utterance.lang = this.options.defaultLang;
            utterance.rate = this.currentRate;  // 应用当前语速
            
            const voice = this.voices.find(v => v.lang === this.options.defaultLang);
            if (voice) utterance.voice = voice;

            utterance.onend = () => {
                this.removeHighlights();
                currentIndex++;
                readNext();
            };

            this.speechSynthesis.speak(utterance);
        };

        readNext();
    }

    getTextNodes() {
        const nodes = [];
        const walker = document.createTreeWalker(
            this.zoomContainer,
            NodeFilter.SHOW_TEXT,
            {
                acceptNode: function(node) {
                    // 排除脚本标签和工具栏
                    if (node.parentElement.closest('.accessibility-toolbar, script, noscript')) {
                        return NodeFilter.FILTER_REJECT;
                    }
                    // 排除隐藏元素
                    if (node.parentElement.offsetParent === null) {
                        return NodeFilter.FILTER_REJECT;
                    }
                    // 只接受可见文本内容
                    const style = window.getComputedStyle(node.parentElement);
                    if (style.display === 'none' || style.visibility === 'hidden') {
                        return NodeFilter.FILTER_REJECT;
                    }
                    return node.textContent.trim() ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
                }
            }
        );

        let node;
        while (node = walker.nextNode()) {
            // 确保节点是可见的且不在脚本或样式标签中
            const isValidNode = 
                !node.parentElement.closest('script, style, noscript') && 
                node.textContent.trim() &&
                !node.parentElement.getAttribute('aria-hidden');
                
            if (isValidNode) {
                nodes.push(node.parentElement);
            }
        }
        return nodes;
    }

    getNodeText(node) {
        let text = node.textContent.trim();
        
        // 处理图片描述
        if (this.options.imageAltEnabled) {
            const images = node.getElementsByTagName('img');
            for (const img of images) {
                if (img.alt) {
                    text += ` 图片描述：${img.alt}`;
                }
            }
        }
        
        return text;
    }

    // 辅助方法
    highlightNode(node) {
        this.removeHighlights();
        node.classList.add('reading-highlight');
    }

    removeHighlights() {
        const highlighted = document.querySelectorAll('.reading-highlight');
        highlighted.forEach(el => el.classList.remove('reading-highlight'));
    }

    // 添加对比度模式相关方法
    initContrastMode() {
        // 创建样式元素
        const style = document.createElement('style');
        style.id = 'contrast-mode-styles';
        document.head.appendChild(style);
        this.contrastStyleSheet = style;

        // 初始应用正常模式
        this.setContrastMode('normal');
    }

    setContrastMode(mode) {
        if (!this.options.contrastModes[mode]) return;

        this.currentContrastMode = mode;
        const colors = this.options.contrastModes[mode];

        // 更新样式
        this.contrastStyleSheet.textContent = `
            body.contrast-mode-${mode} {
                background-color: ${colors.background} !important;
                color: ${colors.text} !important;
            }
            
            body.contrast-mode-${mode} a {
                color: ${colors.links} !important;
            }
            
            body.contrast-mode-${mode} * {
                background-image: none !important;
                text-shadow: none !important;
                box-shadow: none !important;
            }
            
            body.contrast-mode-${mode} img {
                filter: ${mode === 'normal' ? 'none' : 'grayscale(100%) contrast(120%)'} !important;
            }
            
            body.contrast-mode-${mode} input,
            body.contrast-mode-${mode} button,
            body.contrast-mode-${mode} select,
            body.contrast-mode-${mode} textarea {
                background-color: ${colors.background} !important;
                color: ${colors.text} !important;
                border: 2px solid ${colors.text} !important;
            }
            
            body.contrast-mode-${mode} button:hover,
            body.contrast-mode-${mode} input[type="submit"]:hover {
                background-color: ${colors.text} !important;
                color: ${colors.background} !important;
            }
        `;

        // 移除其他对比度模式的类名
        document.body.className = document.body.className
            .split(' ')
            .filter(c => !c.startsWith('contrast-mode-'))
            .join(' ');

        // 添加当前模式的类名
        document.body.classList.add(`contrast-mode-${mode}`);

        // 更新按钮状态
        const buttons = document.querySelectorAll('.contrast-menu button');
        buttons.forEach(button => {
            button.classList.toggle('active', button.dataset.mode === mode);
        });
    }

    // 添加鼠标悬浮朗读功能
    initHoverRead() {
        if (!this.options.hoverRead) return;

        document.addEventListener('mouseover', (e) => {
            // 清除之前的定时器和朗读
            if (this.hoverTimeout) {
                clearTimeout(this.hoverTimeout);
            }
            if (this.currentHoverUtterance) {
                this.speechSynthesis.cancel(this.currentHoverUtterance);
            }

            // 设置新的定时器
            this.hoverTimeout = setTimeout(() => {
                const text = this.getHoverText(e.target);
                if (text) {
                    this.speakHoverText(text);
                }
            }, this.options.hoverDelay);
        });

        document.addEventListener('mouseout', () => {
            // 鼠标移出时清除定时器和朗读
            if (this.hoverTimeout) {
                clearTimeout(this.hoverTimeout);
            }
            if (this.currentHoverUtterance) {
                this.speechSynthesis.cancel(this.currentHoverUtterance);
            }
        });
    }

    getHoverText(element) {
        let text = '';

        // 处理链接
        if (element.tagName === 'A') {
            text = '链接：';
            // 优先使用 aria-label
            if (element.getAttribute('aria-label')) {
                text += element.getAttribute('aria-label');
            } else {
                text += element.textContent.trim() || element.title || element.href;
            }
        }
        // 处理图片
        else if (element.tagName === 'IMG') {
            text = '图片';
            if (element.alt) {
                text += `：${element.alt}`;
            } else if (element.title) {
                text += `：${element.title}`;
            } else if (element.src) {
                // 从片URL中提取文件名
                const fileName = element.src.split('/').pop().split('.')[0];
                text += `：${fileName}`;
            }
        }
        // 处理按钮
        else if (element.tagName === 'BUTTON' || 
                (element.tagName === 'INPUT' && element.type === 'button')) {
            text = '按钮：';
            text += element.value || element.textContent || element.title || '未命名按钮';
        }
        // 处理输入框
        else if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA') {
            text = '输入框：';
            text += element.placeholder || element.title || element.type || '文本输入';
        }
        // 处理其他可交互元素
        else if (element.hasAttribute('role')) {
            const role = element.getAttribute('role');
            text = `${role}：${element.textContent.trim()}`;
        }
        // 处理有 title 属性的元素
        else if (element.title) {
            text = element.title;
        }

        return text;
    }

    speakHoverText(text) {
        if (!text || !this.speechSynthesis) return;

        const utterance = new SpeechSynthesisUtterance(text);
        utterance.lang = this.options.defaultLang;
        utterance.rate = this.currentRate;  // 应用当前语速
        utterance.volume = 0.8;

        this.currentHoverUtterance = utterance;
        
        utterance.onend = () => {
            this.currentHoverUtterance = null;
        };

        this.speechSynthesis.speak(utterance);
    }

    // 添加工具栏切换方法
    toggleToolbar() {
        this.isToolbarVisible = !this.isToolbarVisible;
        const toolbar = document.querySelector('.accessibility-toolbar');
        const toggleButton = document.querySelector('.accessibility-toggle');

        if (this.isToolbarVisible) {
            toolbar.classList.remove('hidden');
            toggleButton.classList.add('active');
            // 恢复所有功能
            if (this.options.hoverRead) {
                this.initHoverRead();
            }
        } else {
            toolbar.classList.add('hidden');
            toggleButton.classList.remove('active');
            // 停止所有正在进行的功能
            this.stopReading();
            if (this.currentHoverUtterance) {
                this.speechSynthesis.cancel(this.currentHoverUtterance);
            }
            // 移除事件监听
            document.removeEventListener('mouseover', this.handleMouseOver);
            document.removeEventListener('mouseout', this.handleMouseOut);
        }
    }

    // 添加语速设置方法
    setRate(rate) {
        if (this.options.speechRates[rate]) {
            this.currentRate = this.options.speechRates[rate];
            
            // 如果正在朗读，应用新的语速
            if (this.isSpeaking) {
                this.stopReading();
                this.startReading();
            }
        }
    }

    // 调整语速的辅助方法
    adjustRate(delta) {
        const currentRate = parseFloat(this.currentRate);
        const newRate = Math.max(0.5, Math.min(2, currentRate + delta));
        this.currentRate = newRate;
        
        if (this.isSpeaking) {
            this.stopReading();
            this.startReading();
        }
        
        this.showShortcutFeedback(`语速: ${newRate.toFixed(1)}x`);
    }

    // 添加选择文本朗读功能
    initSelectionRead() {
        document.addEventListener('mouseup', () => {
            if (!this.options.selectionRead) return;

            const selection = window.getSelection();
            const text = selection.toString().trim();

            if (text && !this.isToolbarElement(selection.anchorNode)) {
                // 创建朗读按钮
                this.showSelectionReadButton(text, selection);
            } else {
                this.hideSelectionReadButton();
            }
        });

        document.addEventListener('mousedown', (e) => {
            if (!e.target.classList.contains('selection-read-button')) {
                this.hideSelectionReadButton();
            }
        });
    }

    showSelectionReadButton(text, selection) {
        this.hideSelectionReadButton();

        const button = document.createElement('button');
        button.className = 'selection-read-button';
        button.innerHTML = '朗读选中文本';
        
        const range = selection.getRangeAt(0);
        const rect = range.getBoundingClientRect();
        
        button.style.position = 'fixed';
        button.style.left = `${rect.left + window.scrollX}px`;
        button.style.top = `${rect.bottom + window.scrollY + 5}px`;
        
        button.addEventListener('click', () => {
            this.speakText(text);
            this.hideSelectionReadButton();
        });

        document.body.appendChild(button);
    }

    hideSelectionReadButton() {
        const button = document.querySelector('.selection-read-button');
        if (button) {
            button.remove();
        }
    }

    isToolbarElement(node) {
        return node.parentElement?.closest('.accessibility-toolbar, .accessibility-toggle');
    }

    speakText(text) {
        if (!text || !this.speechSynthesis) return;

        const utterance = new SpeechSynthesisUtterance(text);
        utterance.lang = this.options.defaultLang;
        utterance.rate = this.currentRate;
        
        this.speechSynthesis.speak(utterance);
    }

    // 添加新的功能方法
    initFontControl() {
        const style = document.createElement('style');
        style.id = 'accessibility-font-styles';
        document.head.appendChild(style);
        this.fontStyleSheet = style;
    }

    setFont(fontType) {
        this.currentFont = fontType;
        const font = this.options.fonts[fontType];
        
        this.fontStyleSheet.textContent = `
            body {
                font-family: ${fontType === 'default' ? 'inherit' : font} !important;
                ${fontType === 'large' ? `font-size: ${font} !important;` : ''}
                ${fontType === 'spacing' ? `letter-spacing: ${font} !important;` : ''}
            }
        `;
    }

    initSimplifyPage() {
        this.isSimplified = false;
    }

    toggleSimplifiedPage() {
        this.isSimplified = !this.isSimplified;
        document.body.classList.toggle('simplified-page');
        
        if (this.isSimplified) {
            // 移除广告和必要元素
            const elementsToRemove = document.querySelectorAll('aside, .ad, .advertisement, .social-share');
            elementsToRemove.forEach(el => el.style.display = 'none');
        } else {
            // 恢复隐藏的元素
            const hiddenElements = document.querySelectorAll('aside, .ad, .advertisement, .social-share');
            hiddenElements.forEach(el => el.style.display = '');
        }
    }

    initColorFilters() {
        const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
        svg.style.display = 'none';
        svg.innerHTML = `
            <defs>
                <filter id="protanopia">
                    <feColorMatrix type="matrix" values="0.567,0.433,0,0,0 0.558,0.442,0,0,0 0,0.242,0.758,0,0 0,0,0,1,0"/>
                </filter>
                <filter id="deuteranopia">
                    <feColorMatrix type="matrix" values="0.625,0.375,0,0,0 0.7,0.3,0,0,0 0,0.3,0.7,0,0 0,0,0,1,0"/>
                </filter>
                <filter id="tritanopia">
                    <feColorMatrix type="matrix" values="0.95,0.05,0,0,0 0,0.433,0.567,0,0 0,0.475,0.525,0,0 0,0,0,1,0"/>
                </filter>
            </defs>
        `;
        document.body.appendChild(svg);
    }

    setColorFilter(filterType) {
        document.body.style.filter = filterType === 'normal' ? 'none' : `url(#${filterType})`;
        
        // 更新按钮状态
        const buttons = document.querySelectorAll('.filter-menu button');
        buttons.forEach(button => {
            button.classList.toggle('active', button.dataset.filter === filterType);
        });
    }

    initNavigationAssist() {
        const skipLinks = document.createElement('div');
        skipLinks.className = 'skip-links';
        skipLinks.innerHTML = `
            <a href="#main">跳到主要内容</a>
            <a href="#nav">跳到导航菜单</a>
            <a href="#footer">跳到页脚</a>
        `;
        document.body.insertBefore(skipLinks, document.body.firstChild);

        // 添加键盘导航提示
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Tab') {
                document.body.classList.add('show-focus-rings');
            }
        });
        
        document.addEventListener('mousedown', () => {
            document.body.classList.remove('show-focus-rings');
        });
    }

    initAnimationControl() {
        this.isReducedMotion = false;
    }

    toggleReduceMotion() {
        this.isReducedMotion = !this.isReducedMotion;
        document.body.classList.toggle('reduce-motion');
        const button = document.querySelector('.animation-toggle');
        button.textContent = this.isReducedMotion ? '恢复动画' : '减少动画';
        button.classList.toggle('active');
    }

    // 工具方法：显示操作反馈
    showFeedback(message) {
        const feedback = document.createElement('div');
        feedback.className = 'accessibility-feedback';
        feedback.textContent = message;
        document.body.appendChild(feedback);

        setTimeout(() => {
            feedback.classList.add('fade-out');
            setTimeout(() => feedback.remove(), 300);
        }, 1500);
    }

    // 添加纯文本相关方法
    togglePlainText() {
        this.isPlainText = !this.isPlainText;
        const button = document.querySelector('.plain-text');
        button.classList.toggle('active');
        
        if (this.isPlainText) {
            this.applyPlainText();
        } else {
            this.removePlainText();
        }
    }

    applyPlainText() {
        // 保存原始样式以便恢复
        this.originalStyles = {
            images: [],
            backgrounds: []
        };

        // 创建纯文本样式
        const style = document.createElement('style');
        style.id = 'plain-text-style';
        style.textContent = `
            body.plain-text-mode *:not(.accessibility-toolbar):not(.accessibility-toolbar *) {
                font-family: ${this.options.plainTextStyles.fontFamily} !important;
                font-size: ${this.options.plainTextStyles.fontSize} !important;
                line-height: ${this.options.plainTextStyles.lineHeight} !important;
                color: ${this.options.plainTextStyles.color} !important;
                background: ${this.options.plainTextStyles.background} !important;
                border: none !important;
                box-shadow: none !important;
                text-shadow: none !important;
                margin: 0 !important;
                padding: 0 !important;
            }
            
            body.plain-text-mode {
                max-width: 800px !important;
                margin: 0 auto !important;
                padding: 20px !important;
            }
            
            /* 保持工具栏样式 */
            body.plain-text-mode .accessibility-toolbar {
                position: fixed !important;
                top: 0 !important;
                left: 0 !important;
                right: 0 !important;
                background: #333333 !important;
                padding: 4px !important;
                display: flex !important;
                flex-direction: row !important;
                gap: 4px !important;
                justify-content: center !important;
                align-items: center !important;
                z-index: 9999 !important;
                margin: 0 !important;
                width: 100% !important;
                max-width: none !important;
            }
            
            body.plain-text-mode .accessibility-toolbar button {
                min-width: 40px !important;
                height: 40px !important;
                padding: 8px !important;
                border: none !important;
                border-radius: 4px !important;
                background: #4d4d4d !important;
                color: white !important;
                font-size: 12px !important;
                display: flex !important;
                flex-direction: column !important;
                align-items: center !important;
                justify-content: center !important;
                gap: 2px !important;
                margin: 0 !important;
            }
            
            body.plain-text-mode .accessibility-toolbar button.active {
                background: #ff6b00 !important;
            }
            
            body.plain-text-mode .accessibility-toolbar button:hover {
                background: #666666 !important;
            }
            
            /* 保持菜单样式 */
            body.plain-text-mode .contrast-menu,
            body.plain-text-mode .rate-menu,
            body.plain-text-mode .font-menu,
            body.plain-text-mode .filter-menu {
                position: absolute !important;
                top: 100% !important;
                left: 50% !important;
                transform: translateX(-50%) !important;
                background: #4d4d4d !important;
                padding: 4px !important;
                border-radius: 4px !important;
                margin-top: 4px !important;
                width: 140px !important;
            }
            
            body.plain-text-mode .contrast-menu button,
            body.plain-text-mode .rate-menu button,
            body.plain-text-mode .font-menu button,
            body.plain-text-mode .filter-menu button {
                width: 100% !important;
                padding: 8px 12px !important;
                text-align: left !important;
                background: transparent !important;
                color: white !important;
                border: none !important;
                border-radius: 2px !important;
            }
            
            /* 其他内容样式 */
            body.plain-text-mode p,
            body.plain-text-mode div:not(.accessibility-toolbar):not(.accessibility-toolbar *),
            body.plain-text-mode h1,
            body.plain-text-mode h2,
            body.plain-text-mode h3,
            body.plain-text-mode h4,
            body.plain-text-mode h5,
            body.plain-text-mode h6 {
                margin-bottom: 1em !important;
            }
            
            body.plain-text-mode a {
                color: #0000EE !important;
                text-decoration: underline !important;
            }
            
            body.plain-text-mode img {
                display: none !important;
            }
        `;
        
        document.head.appendChild(style);
        document.body.classList.add('plain-text-mode');

        // 处理图片
        const images = document.getElementsByTagName('img');
        for (let img of images) {
            if (img.alt) {
                const altText = document.createElement('span');
                altText.className = 'img-alt-text';
                altText.textContent = `[图片: ${img.alt}]`;
                img.parentNode.insertBefore(altText, img);
            }
        }

        // 移除不必要元素
        const elementsToRemove = document.querySelectorAll('style:not(#plain-text-style), iframe, video, audio, canvas, svg');
        elementsToRemove.forEach(el => {
            el.style.display = 'none';
        });
    }

    removePlainText() {
        // 移除文本样式
        const style = document.getElementById('plain-text-style');
        if (style) {
            style.remove();
        }
        document.body.classList.remove('plain-text-mode');

        // 移除图片替代文
        const altTexts = document.getElementsByClassName('img-alt-text');
        while (altTexts.length > 0) {
            altTexts[0].remove();
        }

        // 恢复隐藏的元素
        const hiddenElements = document.querySelectorAll('style, iframe, video, audio, canvas, svg');
        hiddenElements.forEach(el => {
            el.style.display = '';
        });
    }

    // 添加阅读指引器相关方法
    toggleReadingGuide() {
        this.isReadingGuideActive = !this.isReadingGuideActive;
        const button = document.querySelector('.reading-guide');
        button.classList.toggle('active');

        if (this.isReadingGuideActive) {
            this.createReadingGuide();
        } else {
            this.removeReadingGuide();
        }
    }

    createReadingGuide() {
        const guide = document.createElement('div');
        guide.className = 'reading-guide-mask';
        document.body.appendChild(guide);

        const updateGuidePosition = (e) => {
            const height = parseInt(this.options.readingGuide.height);
            const mouseY = e.clientY;
            
            guide.style.cssText = `
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100vh;
                pointer-events: none;
                z-index: 9998;
                background: linear-gradient(
                    to bottom,
                    rgba(0,0,0,0.3) 0,
                    rgba(0,0,0,0.3) ${mouseY - height/2}px,
                    ${this.options.readingGuide.color} ${mouseY - height/2}px,
                    ${this.options.readingGuide.color} ${mouseY + height/2}px,
                    rgba(0,0,0,0.3) ${mouseY + height/2}px,
                    rgba(0,0,0,0.3) 100%
                );
            `;

            // 添加高亮条
            const highlightBar = document.createElement('div');
            highlightBar.className = 'reading-guide-highlight';
            highlightBar.style.cssText = `
                position: fixed;
                top: ${mouseY - height/2}px;
                left: 0;
                width: 100%;
                height: ${height}px;
                border-top: 2px solid ${this.options.readingGuide.borderColor};
                border-bottom: 2px solid ${this.options.readingGuide.borderColor};
                pointer-events: none;
                z-index: 9999;
            `;

            // 移除旧的高亮条
            const oldHighlight = document.querySelector('.reading-guide-highlight');
            if (oldHighlight) {
                oldHighlight.remove();
            }
            document.body.appendChild(highlightBar);
        };

        document.addEventListener('mousemove', updateGuidePosition);
        this.guideUpdateHandler = updateGuidePosition;
    }

    removeReadingGuide() {
        const guide = document.querySelector('.reading-guide-mask');
        const highlight = document.querySelector('.reading-guide-highlight');
        if (guide) guide.remove();
        if (highlight) highlight.remove();
        
        if (this.guideUpdateHandler) {
            document.removeEventListener('mousemove', this.guideUpdateHandler);
        }
    }

    // 添加销毁方法
    destroy() {
        try {
            // 移除事件监听
            document.removeEventListener('mousemove', this.guideUpdateHandler);
            document.removeEventListener('mouseup', this.selectionReadHandler);
            
            // 停止所有朗读
            if (this.speechSynthesis) {
                this.speechSynthesis.cancel();
            }

            // 移除工具栏
            const toolbar = document.querySelector('.accessibility-toolbar');
            const toggle = document.querySelector('.accessibility-toggle');
            if (toolbar) toolbar.remove();
            if (toggle) toggle.remove();

            // 移除样式
            const styles = document.querySelectorAll('style[id^="accessibility-"]');
            styles.forEach(style => style.remove());

            // 恢复原始状态
            document.body.classList.remove('plain-text-mode', 'reduce-motion');
            if (this.zoomContainer) {
                while (this.zoomContainer.firstChild) {
                    document.body.appendChild(this.zoomContainer.firstChild);
                }
                this.zoomContainer.remove();
            }
        } catch (error) {
            console.error('无障碍助手清理失败:', error);
        }
    }

    // 添加重置方法
    reset() {
        try {
            // 重置所有状态
            this.currentZoom = 1;
            this.isSpeaking = false;
            this.currentContrastMode = 'normal';
            this.isToolbarVisible = this.options.initiallyVisible;
            this.currentRate = this.options.speechRates[this.options.defaultRate];
            this.currentFont = 'default';
            this.isPlainText = false;
            this.isReadingGuideActive = false;

            // 移除所有效果
            this.removePlainText();
            this.removeReadingGuide();
            this.applyZoom();
            document.body.style.filter = 'none';

            // 更新按钮状态
            const buttons = document.querySelectorAll('.accessibility-toolbar button');
            buttons.forEach(button => button.classList.remove('active'));
        } catch (error) {
            console.error('无障碍助手重置失败:', error);
        }
    }
} 